package com.edu.chat.web.config.Interceptor;

import com.edu.buservice.util.model.TenantUtil;
import com.edu.chat.web.config.CommonConfig;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 公海租户拦截器
 */
@Component
@Slf4j
@Order(Ordered.LOWEST_PRECEDENCE)
public class PublicTenantInterceptor implements HandlerInterceptor {

	// 公海租户标识的请求头名称
	private static final String PUBLIC_TENANT_HEADER = "X-Public-Tenant";


	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response,
							 Object handler) throws Exception {
		log.info("------------------------公海租户上下文拦截器---------------------------------");
		// 检查请求头是否包含公海租户标识
		if (isPublicTenantRequest(request)) {
			// 设置租户上下文
			TenantUtil.setCurrentTenantId(CommonConfig.PUBLIC_TENANT_ID);
		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
								HttpServletResponse response,
								Object handler, Exception ex) {
	}

	private boolean isPublicTenantRequest(HttpServletRequest request) {
		String headerValue = request.getHeader(PUBLIC_TENANT_HEADER);
		return headerValue != null && !headerValue.isEmpty();
	}
}